package com.itbaima.interceptor;

import com.itbaima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否为空
        if (!StringUtils.hasText(token)) {
            // 不放行
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
//            return false;
            throw new RuntimeException("未登录，请重新登录");
        }
        // 解析token是否成功
        try {
            Claims claims = JwtUtil.parseJWT(token);
//            String subject = claims.getSubject();
//            System.out.println(subject);
        } catch (Exception e) {
            // 若出现了异常则提示重新登录401
            e.printStackTrace();
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
//            return false;
            throw new RuntimeException("未登录，请重新登录");
        }
        // 若解析成功没有出现异常则是登录状态
        return true;
    }
}
